package com.aring.deals.actions;

import java.lang.reflect.Type;

import org.apache.struts2.ServletActionContext;

import com.aring.constant.CommConstant;
import com.aring.constant.ResultCode;
import com.aring.deals.bean.JsonBean;
import com.aring.deals.bean.User;
import com.aring.deals.listener.OptionListener;
import com.aring.deals.option.UserOption;
import com.aring.deals.tool.Common;
import com.google.gson.reflect.TypeToken;
import com.opensymphony.xwork2.ActionContext;

@SuppressWarnings("serial")
public class LoginAction extends BasicAction{
	
   private String account;
   private String password;
   
   public String getAccount() {
	return account;
   }
   
   public void setAccount(String account) {
	this.account = account;
   }
   
   public String getPassword() {
	return password;
   }
   
   public void setPassword(String password) {
	   if(password==null) this.password = password;
	   else this.password = Common.getMD5Str(password);
   }
	
	@Override
	public String execute() throws Exception {
		setOut(ServletActionContext.getResponse().getWriter());
		UserOption.login(account, getPassword(), new OptionListener<User>() {		
		@Override
		public void onSuccess(User user) {
            user.setPassword(null);
            user.setWithdrawPassword(null);
            user.setProductOrders(null);
            user.setWithdrawOrders(null);
		    JsonBean<User> json = new JsonBean<User>();
		    ActionContext.getContext().getSession().put(CommConstant.SESSION_USER_ID, user.getId());
		    json.setResultCode(ResultCode.SUCCESS_CODE);
		    json.setResult(user);
		    Type type = new TypeToken<JsonBean<User>>() {}.getType();
		    getOut().write(Common.<JsonBean<User>>packageJson(json, type)); 
			getOut().flush();
			getOut().close();
		}
		
		@Override
		public void onFailure(int resultCode) {
			JsonBean<String> json = new JsonBean<String>();
		    json.setResultCode(resultCode);
		    Type type = new TypeToken<JsonBean<String>>() {}.getType();
			getOut().write(Common.packageJson(json, type)); 
			getOut().flush();
			getOut().close();
		}
	});
		return null;
	}
	
	
}
